package com.youlu.campus.service.activity.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.activity.service.UserActivityTaskRankingService;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.base.exception.MobileUserException;
import com.youlu.campus.base.exception.MobileUserNotFoundException;
import com.youlu.campus.base.exception.UserNotFoundException;

import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.ActivityTaskInfo;
import com.youlu.campus.entity.ActivityUserRecord;
import com.youlu.campus.entity.CaCertificateLog;
import com.youlu.campus.entity.CaGroupInfo;
import com.youlu.campus.entity.CertificateActivityConfig;
import com.youlu.campus.entity.ModifyActivityUserLog;
import com.youlu.campus.entity.OrderInfo;
import com.youlu.campus.entity.PayConfigPage;
import com.youlu.campus.entity.TaskValueTag;
import com.youlu.campus.entity.UniversityInfo;
import com.youlu.campus.entity.UserPO;
import com.youlu.campus.entity.VO.req.ImportActivityPlatformVO;
import com.youlu.campus.entity.VO.req.ImportUserActivityQVO;
import com.youlu.campus.entity.VO.req.ImportUserCertificateVO;
import com.youlu.campus.entity.VO.req.PlatformActivityQueryVO;
import com.youlu.campus.entity.VO.res.UserCaInfoRes;
import com.youlu.campus.entity.VO.res.UserJoinActivityCaRes;
import com.youlu.campus.entity.WechatH5UserPO;
import com.youlu.campus.entity.english.vo.response.CompetitionUserInviteResponse;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.service.activity.ActivityTaskService;
import com.youlu.campus.service.ca.impl.UserCaRecordService;
import com.youlu.campus.service.cache.CacheActivityService;
import com.youlu.campus.service.cache.CacheActivityUserRecordService;
import com.youlu.campus.service.cache.CachePayConfigService;
import com.youlu.campus.service.cache.CacheUserService;
import com.youlu.campus.service.english.CompetitionUserInviteService;
import com.youlu.campus.service.invite.UserInviteRecordService;
import com.youlu.campus.service.order.OrderService;
import com.youlu.campus.service.ranking.entity.UserActivityTaskRanking;
import com.youlu.campus.service.university.UniversityInfoService;
import com.youlu.campus.service.visitor.UserInfoExtendService;
import com.youlu.campus.service.wechat.WechatH5Service;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PlatformOtherActivityService {

    /**
     * 批量处理 一次处理的 数量
     */
    private static final int BATCH_LIMIT = 2000;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Lazy
    @Autowired
    private CacheActivityUserRecordService cacheActivityUserRecordService;

    @Autowired
    private CacheUserService cacheUserService;

    @Autowired
    private CachePayConfigService cachePayConfigService;

    @Autowired
    private CacheActivityService cacheActivityService;

    @Autowired
    private UserInfoExtendService userInfoExtendService;

    @Autowired
    private WechatH5Service wechatH5Service;


    @Autowired
    private UniversityInfoService universityInfoService;


    private static final Integer SCORE = 500;

    @Lazy
    @Autowired
    private ActivityTaskService activityTaskService;

    @Lazy
    @Autowired
    private CompetitionUserInviteService competitionUserInviteService;

    @Lazy
    @Autowired
    private UserInviteRecordService userInviteRecordService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Lazy
    @Autowired
    private OrderService orderService;
    @Lazy
    @Autowired
    private UserCaRecordService userCaRecordService;

    @Autowired
    private UserActivityTaskRankingService userActivityTaskRankingService;

    private final String CA_CERTIFICATE_LOCK = "time-digital-ca:certificate:activityId.%s:mobile.%s";


    public void updateUserInfo(UserPO userInfo, String activityId) {
        try {
            if (StringUtils.isAnyBlank(userInfo.getName(),
                    userInfo.getUniversityName(),
                    userInfo.getUniversityId(),
                    userInfo.getOpenId(),
                    userInfo.getMobile())) {
                log.error("H5活动实时领取电子证书相关参数未空 activityId:{},user:{}", activityId, JSON.toJSONString(userInfo));
                return;
            }
            ActivityInfo activityInfo = this.mongoTemplate.findById(activityId, ActivityInfo.class);
            if (Objects.isNull(activityInfo)) {
                log.error("活动找不到 activityId:{}", activityId);
                return;
            }
            if (!activityInfo.getVolunteerTimeDigitalCa()) {
                log.error("活动未开启实时领取电子证书 activityId:{} | volunteerTimeDigitalCa:{}", activityId,
                        activityInfo.getVolunteerTimeDigitalCa());
                return;
            }
            if (MapUtils.isEmpty(activityInfo.getCaMatchKeyWords())) {
                log.error("活动未配置证书关键字 activityId:{}", activityId);
                return;
            }
            //如果邀请来用户直接请求更新无需分布式锁
            if (!userInfo.getH5SignUp()) {
                //添加分布式锁
                String lockKey = String.format(CA_CERTIFICATE_LOCK, activityId, userInfo.getMobile());
                log.info("【更新实时领取】获取锁->{}", lockKey);
                Boolean existKey = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 3L, TimeUnit.HOURS);
                log.info("【更新实时领取】获取锁状态->{}", existKey);
                if (Objects.nonNull(existKey) && !existKey) {
                    log.error("实时领取电子证书频繁请求 activityId:{}", activityId);
                    return;
                }
            }
            UserActivityTaskRanking userActivityTaskRanking = userActivityTaskRankingService.findByUserIdAndActivityId(userInfo.getId(), activityId);
            if (Objects.isNull(userActivityTaskRanking)) {
                log.error("用户未有贡献值 activityId:{}|userId:{}", activityId, userInfo.getId());
                return;
            }
            int quantity = userActivityTaskRanking.getQuantity().intValue();
            if (userActivityTaskRanking.getQuantity().intValue() == 0) {
                log.error("用户贡献值为0 activityId:{}|userId:{}", activityId, userInfo.getId());
                return;
            }
            ActivityTaskInfo activityTaskInfo = activityTaskService.find(activityId, TaskBizType.INVITE);
            Long inviteUserCount = userInviteRecordService.getInviteUserCount(userInfo.getId(), activityId,
                    activityTaskInfo.getId(), Boolean.TRUE);
            String keyWord = activityInfo.getCaMatchKeyWords().get("invite");
            CompetitionUserInviteResponse competitionUserInvite = new CompetitionUserInviteResponse();
            competitionUserInvite.setInviteValue(quantity);
            competitionUserInviteService.matchRule(activityTaskInfo, activityId, competitionUserInvite);
            String caLevel = competitionUserInvite.getCaLevel();
            Integer priority = competitionUserInvite.getPriority();
            if (StringUtils.isBlank(caLevel) || "暂无证书".equals(caLevel) || 1 == priority) {
                log.error(":>>> 用户:{} 活动:{} 获取暂无证书 priority:{}", userInfo.getOpenId(), activityId, priority);
                return;
            }
            Date now = new Date();
            Update update = new Update();
            Query query = new Query();
            query.addCriteria(Criteria.where("mobile").is(userInfo.getMobile()));
            query.addCriteria(Criteria.where("activityId").is(activityId));
            query.addCriteria(Criteria.where("taskBizType").is(keyWord));
            //query.addCriteria(Criteria.where("caLevel").is(caLevel));
            ActivityUserRecord exists = this.mongoTemplate.findOne(query, ActivityUserRecord.class);
            if (Objects.nonNull(exists)) {
                log.error(":>>> 用户:{} 活动:{} 已存在 证书类型:{}等级:{}", userInfo.getId(), activityId, keyWord, caLevel);
                update.set("updatedTime", now);
                Boolean updatePro = Boolean.FALSE;
                if (quantity > exists.getQ()) {
                    update.set("q", quantity);
                    updatePro = Boolean.TRUE;
                }
                if (inviteUserCount.intValue() > exists.getInvitationCount()) {
                    update.set("invitationCount", inviteUserCount.intValue());
                    updatePro = Boolean.TRUE;
                }
                if (!exists.getCaLevel().equals(caLevel)) {
                    update.set("caLevel", caLevel);
                    updatePro = Boolean.TRUE;
                }
                if (updatePro) {
                    this.mongoTemplate.updateMulti(query, update, ActivityUserRecord.class);
                }
                return;
            }
            update.setOnInsert("createdTime", now);
            update.set("updatedTime", now);
            update.set("caLevel", caLevel);
            update.set("openId", userInfo.getOpenId());
            update.set("appId", userInfo.getAppId());
            update.set("unionId", userInfo.getUnionId());
            update.set("universityId", userInfo.getUniversityId());
            update.set("universityName", userInfo.getUniversityName());
            update.set("name", userInfo.getName());
            update.set("userId", userInfo.getId());
            update.set("score", 400);
            update.set("q", quantity);
            update.set("invitationCount", inviteUserCount.intValue());
            FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
            findAndModifyOptions.upsert(Boolean.TRUE);
            findAndModifyOptions.returnNew(Boolean.TRUE);
            this.mongoTemplate.findAndModify(query, update, findAndModifyOptions, ActivityUserRecord.class);
        } catch (Exception e) {
            log.error("【实时更新电子证书错误】activityId:{},userId:{}", activityId, userInfo.getId(), e);
        }

    }

    public void batchDelete(String activityId, String taskBizType, String caLevel) {
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").is(activityId));
        if (StringUtils.isNotBlank(taskBizType)) {
            query.addCriteria(Criteria.where("taskBizType").is(taskBizType));
        }
        if (StringUtils.isNotBlank(caLevel)) {
            query.addCriteria(Criteria.where("caLevel").is(caLevel));
        }
        BulkOperations bulkOperations = this.mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED,
                ActivityUserRecord.class);
        bulkOperations.remove(query);
        bulkOperations.execute();
        log.info("批量删除活动:{}", activityId);
    }

    public Long batchCount(String activityId, String taskBizType, String caLevel) {
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").is(activityId));
        if (StringUtils.isNotBlank(taskBizType)) {
            query.addCriteria(Criteria.where("taskBizType").is(taskBizType));
        }
        if (StringUtils.isNotBlank(caLevel)) {
            query.addCriteria(Criteria.where("caLevel").is(caLevel));
        }
        Long c = this.mongoTemplate.count(query, ActivityUserRecord.class);
        return c;
    }


    public void importUserCertificate(List<ImportUserCertificateVO> importUserCertificateList) {
        log.info("start 导入用户证书");
        Integer limit = 2000;
        Integer skip = 0;
        List<ImportUserCertificateVO> limitRecord = null;
        do {
            log.info("开始批量处理list中第 {} 页 数据 总数据大小 - > {}", skip, importUserCertificateList.size());
            limitRecord =
                    importUserCertificateList.stream().skip(skip * limit).limit(limit).collect(Collectors.toList());
            List<CaCertificateLog> insertList = new LinkedList();
            limitRecord.stream().forEach(userCertificate -> {
                String appId = userCertificate.getAppId();
                String activityId = userCertificate.getActivityId();
                String caLevel = userCertificate.getCaLevel();
                String certificateNo = userCertificate.getCertificateNo();
                String name = userCertificate.getName();
                String mobile = userCertificate.getMobile();
                String taskBizType = userCertificate.getTaskBizType();
                log.info("应用->{} 姓名->{} 手机号->{} 活动 ->{}", appId, name, mobile, activityId);
                Query query = new Query();
                query.addCriteria(Criteria.where("mobile").is(mobile));
                query.addCriteria(Criteria.where("activityId").is(activityId));
                query.addCriteria(Criteria.where("taskBizType").is(taskBizType));
                query.addCriteria(Criteria.where("caLevel").is(caLevel));
                ActivityUserRecord activityUserRecord = this.mongoTemplate.findOne(query, ActivityUserRecord.class);
                if (Objects.isNull(activityUserRecord)) {
                    log.error("应用->{} 姓名->{} 手机号->{} 不存在", appId, name, mobile);
                    return;
                }
                String openId = activityUserRecord.getOpenId();
                WechatH5UserPO user = cacheUserService.findByOpenId(activityUserRecord.getAppId(), openId);
                if (Objects.isNull(user)) {
                    log.error("应用->{} 姓名->{} 手机号->{}  openid ->{}不存在", appId, name, mobile, openId);
                    return;
                }
                query = new Query();
                query.addCriteria(Criteria.where("activityId").is(activityId));
                query.addCriteria(Criteria.where("userId").is(user.getId()));
                query.addCriteria(Criteria.where("caType").is(taskBizType));
                query.addCriteria(Criteria.where("caLevel").is(caLevel));
                CaCertificateLog caCertificateLog = this.mongoTemplate.findOne(query, CaCertificateLog.class);
                if (Objects.nonNull(caCertificateLog)) {
                    log.error("姓名->{} 手机号->{}  openid ->{}存在证书编号", appId, name, mobile, openId);
                    return;
                }
                caCertificateLog = new CaCertificateLog();
                caCertificateLog.setCertificateNo(certificateNo);
                caCertificateLog.setActivityId(activityId);
                caCertificateLog.setCaLevel(caLevel);
                caCertificateLog.setCaType(taskBizType);
                caCertificateLog.setUserId(user.getId());
                insertList.add(caCertificateLog);
            });
            this.mongoTemplate.insertAll(insertList);
            skip++;
        } while (Objects.nonNull(limitRecord) && !limitRecord.isEmpty());


    }


    public Page<ActivityUserRecord> list(PlatformActivityQueryVO platformActivityQuery) {
        Query query = new Query();
        String name = platformActivityQuery.getName();
        boolean choiced = false;
        if (StringUtils.isNotBlank(name)) {
//            Pattern pattern = Pattern.compile("^.*" + name + ".*$", Pattern.CASE_INSENSITIVE);
//            query.addCriteria(Criteria.where("name").regex(pattern));
            query.addCriteria(Criteria.where("name").is(name));
            choiced = true;
        }
        String mobile = platformActivityQuery.getMobile();
        if (StringUtils.isNotBlank(mobile)) {
            query.addCriteria(Criteria.where("mobile").is(mobile));
            choiced = true;
        }
        String openId = platformActivityQuery.getOpenid();
        if (StringUtils.isNotBlank(openId)) {
            query.addCriteria(Criteria.where("openId").is(openId));
            choiced = true;
        }
        if (StringUtils.isNotBlank(platformActivityQuery.getActivityId())) {
            query.addCriteria(Criteria.where("activityId").is(platformActivityQuery.getActivityId()));
            choiced = true;
        }
        long count;
        if (!choiced) {
            count = 1000l;
        } else {
            count = this.mongoTemplate.count(query, ActivityUserRecord.class);
        }

        PageRequest pageRequest = PageRequest.of(platformActivityQuery.getPageNo() - 1,
                platformActivityQuery.getPageSize());
        if (count == 0) {
            return PageableExecutionUtils.getPage(new ArrayList<>(), pageRequest, () -> count);
        }
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        query.with(pageRequest);
        List<ActivityUserRecord> list = this.mongoTemplate.find(query, ActivityUserRecord.class);
        list.stream().forEach(activityUserRecord -> {
            String activityId = activityUserRecord.getActivityId();
            ActivityInfo activityInfo = this.mongoTemplate.findById(activityId, ActivityInfo.class);
            if (Objects.nonNull(activityInfo)) {
                activityUserRecord.setActivityName(activityInfo.getName());
            }
        });
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }


    public boolean update(UserCaInfoRes req, String userId, String openId) {
        String requestParams = JSON.toJSONString(req);
        log.info("更新活动用户信息- >{}", requestParams);
        String mobile = req.getMobile();
        Boolean mobileVerify = req.getMobileVerify();
        ActivityUserRecord up = null;
        if (StringUtils.isNotBlank(mobile) && StringUtils.isNotBlank(req.getAddress())) {
            if (req.getAddress().contains(mobile)) {
                log.error(":>>> 详细地址:{} 中包含手机号:{}", req.getAddress(), mobile);
                throw new BusinessException("详细地址中请勿填写手机号!");
            }
        }
        if (StringUtils.isNotBlank(mobile) && mobileVerify) {
            up = cacheActivityUserRecordService.findByActivityIdAndMobile(req.getActivityId(), mobile,
                    req.getTaskBizType());
        } else {
            up = cacheActivityUserRecordService.findByActivityIdAndOpenId(req.getActivityId(), openId,
                    req.getTaskBizType());
        }
        if (Objects.isNull(up)) {
            log.error(":>>> 用户:{} 未报名活动:{}", openId, req.getActivityId());
            throw new BusinessException("用户未报名活动");
        }
        Query queryUp = null;
        if (StringUtils.isNotBlank(mobile) && mobileVerify) {
            queryUp =
                    new Query().addCriteria(Criteria.where("mobile").is(mobile).and("activityId").is(req.getActivityId()));
        } else {
            queryUp =
                    new Query().addCriteria(Criteria.where("openId").is(openId).and("activityId").is(req.getActivityId()));
        }
        log.info("获取参与活动 ->{} 用户->{} 证书类型->{}", req.getActivityId(), openId, req.getTaskBizType());

        Update update = new Update();
        if (StringUtils.isNotBlank(req.getUniversityId())) {
            update.set("universityId", req.getUniversityId());
            if (StringUtils.isNotBlank(req.getUniversityName())) {
                update.set("universityName", req.getUniversityName());
            }
        }
        if (StringUtils.isNotBlank(req.getName())) {
            update.set("name", req.getName());
        }
        update.set("recieveName", req.getRecieveName());
        update.set("recieveMobile", req.getRecieveMobile());
        update.set("province", req.getProvince());
        update.set("city", req.getCity());
        update.set("area", req.getArea());
        if (StringUtils.isNotBlank(req.getAddress())) {
            update.set("address", req.getAddress());
        }

        UpdateResult updateResult = mongoTemplate.updateMulti(queryUp, update, ActivityUserRecord.class);
        log.info("用户->{}更新地址返回结果->{}", openId, updateResult.getModifiedCount());
        if (updateResult.getModifiedCount() > 0) {
            ModifyActivityUserLog modifyActivityUserLog = new ModifyActivityUserLog();
            modifyActivityUserLog.setPreRecord(up);
            modifyActivityUserLog.setCurrentUserId(userId);
            modifyActivityUserLog.setCurrentOpenId(openId);
            modifyActivityUserLog.setActivityId(req.getActivityId());
            modifyActivityUserLog.setRequestParams(requestParams);
            mongoTemplate.save(modifyActivityUserLog);
            up.setProvince(req.getProvince());
            up.setCity(req.getCity());
            up.setArea(req.getArea());
            up.setRecieveMobile(req.getRecieveMobile());
            up.setRecieveName(req.getRecieveName());
            up.setAddress(req.getAddress());
            if (StringUtils.isNotBlank(req.getUniversityId())) {
                up.setUniversityId(req.getUniversityId());
            }
            if (StringUtils.isNotBlank(req.getUniversityName())) {
                up.setUniversityName(req.getUniversityName());
            }
            UserPO currentUser = req.getCurrentUser();
            currentUser.setProvince(req.getProvince());
            currentUser.setCity(req.getCity());
            currentUser.setArea(req.getArea());
            currentUser.setFullAddress(req.getAddress());
            currentUser.setReceiveMobile(req.getRecieveMobile());
            currentUser.setReceiveName(req.getRecieveName());
            currentUser.setRankNickName(req.getRecieveMobile());
            currentUser.setH5SignUp(Boolean.TRUE);
            userInfoExtendService.saveOrUpdate(currentUser);
            //cacheActivityUserRecordService.removeOpenId(up.getActivityId(), up.getOpenId(), up.getTaskBizType());
            //cacheActivityUserRecordService.removeMobile(up.getActivityId(), up.getMobile(), up.getTaskBizType());
            cacheActivityUserRecordService.putActivityIdAndOpenId(up);
            cacheActivityUserRecordService.putActivityIdAndMobile(up);
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }


    public ActivityUserRecord findByOpenidOrMoble(String activityId, String openId, String mobile, String taskBizType) {
        log.info("查询第三方导入数据信息 openid - > {} , mobile - > {}, 证书等级->{}", openId, mobile, taskBizType);
        if (StringUtils.isEmpty(taskBizType)) {
            throw new BusinessException("证书等级不能为空");
        }
        ActivityUserRecord activityUserRecord = null;
        if (StringUtils.isNotBlank(mobile)) {
            activityUserRecord = findByMobile(activityId, mobile, taskBizType, openId);
            if (Objects.isNull(activityUserRecord)) {
                log.info(":>>> 警告警告---手机号不为空，但是查询不到数据，通过openId查询:{},{},{},{}",
                        activityId, mobile, openId, taskBizType);
                activityUserRecord = findByOpenId(activityId, openId, taskBizType);
            }
        } else {
            activityUserRecord = findByOpenId(activityId, openId, taskBizType);
        }
        return activityUserRecord;
    }

    public List<ActivityUserRecord> findByOpenidOrMoble(String activityId, String openId, String mobile) {
        log.info("查询第三方导入数据信息 openid - > {} , mobile - > {}", openId, mobile);
        Date date = new Date();
        List<ActivityUserRecord> records = new ArrayList<>();
        if (StringUtils.isNotBlank(mobile)) {
            Query query = new Query();
            query.addCriteria(Criteria.where("mobile").is(mobile).and("activityId").is(activityId));
            records = mongoTemplate.find(query, ActivityUserRecord.class);
            if (Objects.isNull(records) || CollectionUtils.isEmpty(records)) {
                log.info(":>>> 用户通过手机号查询证书记录为空:{},{},{}", activityId, openId, mobile);
                Query query1 = new Query();
                query1.addCriteria(Criteria.where("openId").is(openId).and("activityId").is(activityId));
                records = mongoTemplate.find(query1, ActivityUserRecord.class);
            }
        } else {
            Query query = new Query();
            query.addCriteria(Criteria.where("openId").is(openId).and("activityId").is(activityId));
            records = mongoTemplate.find(query, ActivityUserRecord.class);
        }
        log.info("查询第三方导入数据信息 openid - > {} , mobile - > {},耗时:{} 毫秒,数据长度:{}", openId, mobile,
                (System.currentTimeMillis() - date.getTime()) / 1000, records.size());
        return records;
    }

    public ActivityUserRecord findByOpenId(String activityId, String openId, String taskBizType) {
        ActivityUserRecord activityUserRecord = cacheActivityUserRecordService.findByActivityIdAndOpenId(activityId, openId, taskBizType);
        if (Objects.isNull(activityUserRecord)) {
            log.warn("活动->{} openId->{} taskBizType->{} 不存在openid", activityId, openId, taskBizType);
            throw new UserNotFoundException("您未参与活动");
        }
        return activityUserRecord;

    }

    public UserJoinActivityCaRes findByActivityIdAndOpenId(String activityId, String openId, Integer rewardType) {
        PayConfigPage payConfigPage = cachePayConfigService.findByActivityId(activityId);
        if (Objects.isNull(payConfigPage)) {
            throw new BusinessException("支付配置页不存在");
        }
        ActivityInfo activityInfo = cacheActivityService.findById(activityId);
        UserJoinActivityCaRes userJoinActivityCaRes = new UserJoinActivityCaRes();
        Boolean platformSource = payConfigPage.getPlatformSource();
        if (Objects.isNull(platformSource) || platformSource || rewardType == 1) {
            userJoinActivityCaRes.setReceiveCertificateDesc(payConfigPage.getReceiveCertificateDesc());
            userJoinActivityCaRes.setActivityProgress(Boolean.FALSE);
            return userJoinActivityCaRes;
        }

        userJoinActivityCaRes.setBackgroundThemeColor(payConfigPage.getBackgroundThemeColor());
        userJoinActivityCaRes.setLevelColor(payConfigPage.getLevelColor());
        userJoinActivityCaRes.setCountdownColor(payConfigPage.getCountdownColor());
        userJoinActivityCaRes.setReceiveCertificateDesc(payConfigPage.getReceiveCertificateDesc());
        userJoinActivityCaRes.setHideActivityDetailLink(payConfigPage.getHideActivityDetailLink());
        Query query = new Query();
        query.addCriteria(Criteria.where("openId").is(openId));
        query.addCriteria(Criteria.where("activityId").is(activityId));
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ActivityUserRecord> activityUserRecordList = this.mongoTemplate.find(query, ActivityUserRecord.class);
        if (CollectionUtils.isEmpty(activityUserRecordList)) {
            userJoinActivityCaRes.setActivityProgress(Boolean.FALSE);
            return userJoinActivityCaRes;
        }
        if (StringUtils.isNotBlank(payConfigPage.getThemeColor())) {
            userJoinActivityCaRes.setThemeColor(payConfigPage.getThemeColor());
        } else {
            userJoinActivityCaRes.setThemeColor(activityInfo.getThemeColor());
        }
        if (StringUtils.isNotBlank(payConfigPage.getColorValueUserInfo())) {
            userJoinActivityCaRes.setColorValueUserInfo(payConfigPage.getColorValueUserInfo());
        } else {
            userJoinActivityCaRes.setColorValueUserInfo(activityInfo.getColorValueUserInfo());
        }
        WechatH5UserPO userH5 = wechatH5Service.findByOpenId(openId);
        if (Objects.nonNull(userH5)) {
            userJoinActivityCaRes.setNickName(userH5.getNickName());
            userJoinActivityCaRes.setAvatarUrl(userH5.getAvatarUrl());
        }
        userJoinActivityCaRes.setBackGroundImageUrl(payConfigPage.getBackGroundImageUrl());
        userJoinActivityCaRes.setTitle(payConfigPage.getTitle());
        userJoinActivityCaRes.setSubTitle(payConfigPage.getSubTitle());
        userJoinActivityCaRes.setActivityDetailLink(payConfigPage.getActivityDetailLink());
        //分数大于500
        Optional<ActivityUserRecord> gtScore500 =
                activityUserRecordList.stream().filter(user -> user.getScore().intValue() > SCORE).findFirst();
        //分数小于500
        Optional<ActivityUserRecord> ltScore500 =
                activityUserRecordList.stream().filter(user -> user.getScore().intValue() < SCORE).max(Comparator.comparingDouble(ActivityUserRecord::getScore));

        List<TaskValueTag> tagList = new ArrayList<>(3);
        //展示贡献值
        TaskValueTag tag = new TaskValueTag();
        tag.setTitle(payConfigPage.getRewardValueDesc());
        tag.setVal(activityUserRecordList.get(0).getQ().toString());
        tagList.add(tag);
        buildResUserInfo(userJoinActivityCaRes, activityUserRecordList.get(0));
        //大于500
        if (gtScore500.isPresent()) {
            ActivityUserRecord activityUserRecord = gtScore500.get();
            tag = new TaskValueTag();
            tag.setTitle(payConfigPage.getExtDesc());
            tag.setVal(activityUserRecord.getCaLevel());
            tagList.add(tag);
            log.info("活动 - >{} 当前用户 - >{} 大于500 tag {} | {}", activityId, openId, tag.getTitle(), tag.getVal());
        } else {
            tag = new TaskValueTag();
            tag.setTitle(payConfigPage.getExtDesc());
            tag.setVal(payConfigPage.getExtValue());
            tagList.add(tag);
            log.info("活动 - >{} 当前用户 - >{} 不存在大于500 tag {} | {}", activityId, openId, tag.getTitle(), tag.getVal());
        }
        //小于500分
        if (ltScore500.isPresent()) {
            ActivityUserRecord activityUserRecord = ltScore500.get();
            tag = new TaskValueTag();
            tag.setTitle(payConfigPage.getCaLevelDesc());
            tag.setVal(activityUserRecord.getCaLevel());
            tagList.add(tag);
            log.info("活动 - >{} 当前用户 - >{} 小于500 tag {} | {}", activityId, openId, tag.getTitle(), tag.getVal());
        } else {
            tag = new TaskValueTag();
            tag.setTitle(payConfigPage.getCaLevelDesc());
            tag.setVal(payConfigPage.getCaLevelDefaultValue());
            tagList.add(tag);
            log.info("活动 - >{} 当前用户 - >{} 不存在小于500 tag {} | {}", activityId, openId, tag.getTitle(), tag.getVal());
        }
        userJoinActivityCaRes.setTag(tagList);
        return userJoinActivityCaRes;

    }

    private void buildResUserInfo(UserJoinActivityCaRes userJoinActivityCaRes, ActivityUserRecord activityUserRecord) {
        userJoinActivityCaRes.setActivityProgress(Boolean.TRUE);
        userJoinActivityCaRes.setUniversityName(activityUserRecord.getUniversityName());
        userJoinActivityCaRes.setUniversityId(activityUserRecord.getUniversityId());
        userJoinActivityCaRes.setCaLevel(activityUserRecord.getCaLevel());
        userJoinActivityCaRes.setQ(activityUserRecord.getQ());
        userJoinActivityCaRes.setActivityId(activityUserRecord.getActivityId());
        userJoinActivityCaRes.setTaskBizType(activityUserRecord.getTaskBizType());
        userJoinActivityCaRes.setName(activityUserRecord.getName());
    }

    private ActivityUserRecord findByMobile(String activityId, String mobile, String taskBizType, String updateOpenId) {
        ActivityUserRecord activityUserRecord = cacheActivityUserRecordService.findByActivityIdAndMobile(activityId, mobile, taskBizType);
        if (Objects.isNull(activityUserRecord)) {
            String errMsg = "";
            if (taskBizType.equals("QA")) {
                errMsg = "荣誉证书";
            } else if (taskBizType.equals(TaskBizType.INVITE.name())) {
                errMsg = "志愿者证书";
            } else {
                errMsg = taskBizType;
            }
            log.info(":>>> 通过手机号:{}查询数据为空:{}-->:{}", activityId,
                    mobile, taskBizType);
//            return null;
            throw new MobileUserNotFoundException("暂时不满足" + errMsg + "条件，请尝试领取其他证书或确认手机号输入是否正确，如有问题及时联系客服");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("mobile").is(mobile));
        query.addCriteria(Criteria.where("activityId").is(activityId));
        //query.addCriteria(Criteria.where("taskBizType").is(taskBizType));
        Update update = new Update();
        update.set("openId", updateOpenId);
        update.set("userId", updateOpenId);
        update.set("mobileVerify", Boolean.TRUE);
        this.mongoTemplate.updateMulti(query, update, ActivityUserRecord.class);
        cacheActivityUserRecordService.removeMobile(activityId, mobile, taskBizType);
        return activityUserRecord;
    }

    public void updateUserContributionValue(List<ImportUserActivityQVO> importExcelDataList, String activityId) {
        if (CollectionUtils.isEmpty(importExcelDataList)) {
            return;
        }
        Integer limit = 1000;
        Integer skip = 0;
        List<ImportUserActivityQVO> pageExcelDataList = null;
        do {
            log.info("开始批量处理list中第 {} 页 数据 总数据大小 - > {}", skip, importExcelDataList.size());
            pageExcelDataList =
                    importExcelDataList.stream().skip(skip * limit).limit(limit).collect(Collectors.toList());
            List<String> mobileList =
                    pageExcelDataList.stream().map(user -> user.getMobile()).collect(Collectors.toList());
            Query query = new Query();
            query.addCriteria(Criteria.where("mobile").in(mobileList));
            query.addCriteria(Criteria.where("activityId").is(activityId));
            List<ActivityUserRecord> list = this.mongoTemplate.find(query, ActivityUserRecord.class);
            if (CollectionUtils.isNotEmpty(list)) {
                Map<String, List<ActivityUserRecord>> userMobileMap =
                        list.stream().collect(Collectors.groupingBy(ActivityUserRecord::getMobile));
                List<ImportUserActivityQVO> finalPageExcelDataList = pageExcelDataList;
                userMobileMap.forEach((mobile, item) -> {
                    Optional<ImportUserActivityQVO> userExist =
                            finalPageExcelDataList.stream().filter(user -> user.getMobile().equals(mobile)).findFirst();
                    if (userExist.isPresent()) {
                        ImportUserActivityQVO importUserActivity = userExist.get();
                        Query query1 = new Query();
                        query1.addCriteria(Criteria.where("mobile").is(importUserActivity.getMobile()));
                        query1.addCriteria(Criteria.where("activityId").is(activityId));
                        Update update = new Update();
                        update.set("q", importUserActivity.q);
                        UpdateResult updateResult = this.mongoTemplate.updateMulti(query1, update,
                                ActivityUserRecord.class);
                        log.info("导入活动->{} 更新用户->贡献值", activityId, mobile, updateResult.getModifiedCount());
                    }

                });
            }

            skip++;
        } while (Objects.nonNull(pageExcelDataList) && !pageExcelDataList.isEmpty());
        pageExcelDataList.clear();
        importExcelDataList.clear();


    }

    /**
     * 活动证书 批量导入
     *
     * @param importActivityList
     * @param appId
     * @param activityId
     * @param taskBizType
     */
    @Async
    public void otherPlatformActivityImport(List<ImportActivityPlatformVO> importActivityList,
                                            String appId,
                                            String activityId,
                                            String taskBizType) {
        Query queryG = new Query();
        queryG.addCriteria(Criteria.where("activityId").is(activityId).and("taskBizType").is(taskBizType));
        CaGroupInfo g = mongoTemplate.findOne(queryG, CaGroupInfo.class);
        if (Objects.isNull(g)) {
            log.error(":>>> 活动证书序列不存在:{},{}", activityId, taskBizType);
            throw new BusinessException("证书序列不存在:" + taskBizType);
        }
        String gId = g.getId();
        //批量 处理并存储业务
        int forLeng = importActivityList.size() % BATCH_LIMIT == 0 ? importActivityList.size() / BATCH_LIMIT : importActivityList.size() / BATCH_LIMIT + 1;
        for (int i = 0; i < forLeng; i++) {
            int n = i * BATCH_LIMIT;
            List<ImportActivityPlatformVO> limitRecord = importActivityList.stream().skip(n).limit(BATCH_LIMIT).collect(Collectors.toList());
            doOtherPlatformActivityImport(limitRecord, appId, activityId, taskBizType, gId);
        }
    }


    /**
     * 批量处理导入数据
     *
     * @param limitRecord
     * @param appId
     * @param activityId
     * @param taskBizType
     * @param gId
     */
    private void doOtherPlatformActivityImport(List<ImportActivityPlatformVO> limitRecord,
                                               String appId,
                                               String activityId,
                                               String taskBizType,
                                               String gId) {
        if (CollectionUtils.isEmpty(limitRecord)) {
            return;
        }
        //获取所有的openId
        List<String> openIdList = limitRecord.stream().map(ImportActivityPlatformVO::getOpenId).collect(Collectors.toList());
        //通过openId查询用户信息
        Map<String, WechatH5UserPO> userMap = new HashMap<>(0);
        if (CollectionUtils.isNotEmpty(openIdList)) {
            log.info("开始批量获取查询获取用户信息:{}", JSON.toJSON(openIdList));
            Query query = new Query();
            query.addCriteria(Criteria.where("openId").in(openIdList));
            List<WechatH5UserPO> userList = this.mongoTemplate.find(query, WechatH5UserPO.class);
            if (CollectionUtils.isNotEmpty(userList)) {
                userMap = userList.stream().collect(Collectors.toMap(WechatH5UserPO::getOpenId, user -> user, (oldValue, newValue) -> newValue));
            }
        }
        //获取所有没有openId 的手机号
        List<String> mobileList = limitRecord.stream().filter(importData -> StringUtils.isBlank(importData.getOpenId()))
                .map(ImportActivityPlatformVO::getMobile).collect(Collectors.toList());
        Map<String, WechatH5UserPO> mobileMap = new HashMap<>(0);
        if (CollectionUtils.isNotEmpty(mobileList)) {
            log.info("开始批量获取查询获取用户信息:{}", JSON.toJSON(openIdList));
            Query query = new Query();
            query.addCriteria(Criteria.where("mobile").in(mobileList));
            List<WechatH5UserPO> userList = this.mongoTemplate.find(query, WechatH5UserPO.class);
            if (CollectionUtils.isNotEmpty(userList)) {
                mobileMap = userList.stream().collect(Collectors.toMap(WechatH5UserPO::getMobile, user -> user));
            }
        }

        final Map<String, WechatH5UserPO> finalUserMap = userMap;
        final Map<String, WechatH5UserPO> finalMobileMap = mobileMap;

        List<ActivityUserRecord> batchList = Lists.newLinkedList();
        log.info("开始处理导入其他平时用户参与活动数据- > {} ", limitRecord.size());
        limitRecord.stream().forEach(importData -> {
            log.info("otherPlatformActivityImport importData:{}", importData);
            String universityName = importData.getUniversityName();

            ActivityUserRecord insertUserRecord = new ActivityUserRecord();
            insertUserRecord.setAppId(appId);
            insertUserRecord.setActivityId(activityId);
            insertUserRecord.setTaskBizType(taskBizType);
            insertUserRecord.setCaGroupId(gId);
            insertUserRecord.setName(importData.getName());
            insertUserRecord.setMobile(importData.getMobile());
            insertUserRecord.setCaLevel(importData.getCaLevel());
            insertUserRecord.setQ(importData.getQ());
            insertUserRecord.setOpenId(importData.getOpenId());
            insertUserRecord.setInvitationCount(importData.getInvitationCount());
            insertUserRecord.setScore(importData.getScore());
            //查询并更新 学校
            UniversityInfo universityInfo = new UniversityInfo();
            universityInfo.setName(universityName);
            UniversityInfo university = universityInfoService.saveOrUpdate(universityInfo);
            if (Objects.nonNull(university)) {
                insertUserRecord.setUniversityId(university.getId());
            }
            insertUserRecord.setUniversityName(universityName);

            WechatH5UserPO wechatH5UserPO;
            if (StringUtils.isNotBlank(importData.getOpenId())) {
                wechatH5UserPO = finalUserMap.get(importData.getOpenId());
            } else {
                wechatH5UserPO = finalMobileMap.get(importData.getMobile());
            }
            //填充用户数据
            if (Objects.nonNull(wechatH5UserPO)) {
                if (StringUtils.isBlank(insertUserRecord.getOpenId())) {
                    insertUserRecord.setOpenId(wechatH5UserPO.getOpenId());
                }
                insertUserRecord.setUnionId(wechatH5UserPO.getUnionId());
                insertUserRecord.setUserId(wechatH5UserPO.getAccountInfoId());
                insertUserRecord.setProvince(wechatH5UserPO.getProvince());
                insertUserRecord.setCity(wechatH5UserPO.getCity());
                insertUserRecord.setArea(wechatH5UserPO.getArea());
                insertUserRecord.setAddress(wechatH5UserPO.getFullAddress());
                insertUserRecord.setRecieveMobile(wechatH5UserPO.getMobile());
                insertUserRecord.setRecieveName(wechatH5UserPO.getName());
            }
            batchList.add(insertUserRecord);
        });
        this.mongoTemplate.insertAll(batchList);
        batchList.clear();
    }


    private void getBatchUserInfo(List<ActivityUserRecord> insertUserRecordList, List<String> openIdList) {
        if (CollectionUtils.isEmpty(openIdList)) {
            return;
        }
        //通过openId查询用户信息
        log.info("开始批量获取查询获取用户信息:{}", JSON.toJSON(openIdList));
        Query query = new Query();
        query.addCriteria(Criteria.where("openId").in(openIdList));
        List<WechatH5UserPO> userList = this.mongoTemplate.find(query, WechatH5UserPO.class);
        if (CollectionUtils.isEmpty(userList)) {
            return;
        }
        Map<String, WechatH5UserPO> userMap = userList.stream().collect(Collectors.toMap(WechatH5UserPO::getOpenId, user -> user));
        //用户id 赋值
        insertUserRecordList.stream().forEach(activityUserRecord -> {
            if (StringUtils.isNotBlank(activityUserRecord.getOpenId())) {
                WechatH5UserPO wechatH5UserPO = userMap.get(activityUserRecord.getOpenId());
                if (Objects.nonNull(wechatH5UserPO)) {
                    activityUserRecord.setUnionId(wechatH5UserPO.getUnionId());
                    activityUserRecord.setUserId(wechatH5UserPO.getAccountInfoId());
                    activityUserRecord.setProvince(wechatH5UserPO.getProvince());
                    activityUserRecord.setCity(wechatH5UserPO.getCity());
                    activityUserRecord.setArea(wechatH5UserPO.getArea());
                    activityUserRecord.setAddress(wechatH5UserPO.getFullAddress());
                    activityUserRecord.setRecieveMobile(wechatH5UserPO.getMobile());
                    activityUserRecord.setRecieveName(wechatH5UserPO.getName());
                }
            }
        });
        //查询 用户订单信息
        List<String> accountUserIdList = userList.stream().map(user -> user.getAccountInfoId()).collect(Collectors.toList());
        query = new Query();
        query.addCriteria(Criteria.where("accountInfoId").in(accountUserIdList));
        query.addCriteria(Criteria.where("status").ne("0"));
        query.addCriteria(Criteria.where("platform").is("wechat-h5"));
        query.addCriteria(Criteria.where("openId").exists(Boolean.TRUE));
        query.with(Sort.by(Sort.Direction.DESC, "id"));
        List<OrderInfo> orderInfoList = new ArrayList<>();
        try {
            orderInfoList = this.mongoTemplate.find(query, OrderInfo.class);
        } catch (Exception e) {
            log.error(":>>> 订单源数据错误,查询订单错误:{},{}", JSON.toJSON(query), e);
            return;
        }
        if (CollectionUtils.isEmpty(orderInfoList)) {
            return;
        }
        Map<String, OrderInfo> orderInfoMap = orderInfoList.stream().collect(Collectors.toMap(OrderInfo::getOpenId, o -> o));


        Map<String, List<OrderInfo>> mapUserOrder = orderInfoList.stream().collect(Collectors.groupingBy(OrderInfo::getOpenId));
        if (MapUtils.isEmpty(mapUserOrder)) {
            return;
        }
        insertUserRecordList.stream().forEach(activityUserRecord -> {
            if (StringUtils.isNotBlank(activityUserRecord.getOpenId())) {
                List<OrderInfo> orderInfoList2 = mapUserOrder.get(activityUserRecord.getOpenId());
                if (CollectionUtils.isNotEmpty(orderInfoList2)) {
                    OrderInfo orderInfo =
                            orderInfoList2.stream().sorted(Comparator.comparing(OrderInfo::getCreatedTime)).findFirst().orElse(null);
                    if (Objects.nonNull(orderInfo)) {
                        activityUserRecord.setProvince(orderInfo.getProvince());
                        activityUserRecord.setCity(orderInfo.getCity());
                        activityUserRecord.setArea(orderInfo.getArea());
                        activityUserRecord.setAddress(orderInfo.getAddress());
                        activityUserRecord.setRecieveMobile(orderInfo.getMobile());
                        activityUserRecord.setRecieveName(orderInfo.getName());
                        UserPO currentUser = new UserPO();
                        currentUser.setName(activityUserRecord.getName());
                        currentUser.setId(activityUserRecord.getUserId());
                        currentUser.setMobile(activityUserRecord.getMobile());
                        currentUser.setProvince(orderInfo.getProvince());
                        currentUser.setName(activityUserRecord.getName());
                        currentUser.setCity(orderInfo.getCity());
                        currentUser.setArea(orderInfo.getArea());
                        currentUser.setFullAddress(orderInfo.getAddress());
                        currentUser.setReceiveName(orderInfo.getName());
                        currentUser.setReceiveMobile(orderInfo.getMobile());
                        currentUser.setH5SignUp(Boolean.TRUE);
                        userInfoExtendService.saveOrUpdate(currentUser);

                    }
                }
            }
        });
        if (MapUtils.isNotEmpty(mapUserOrder)) {
            mapUserOrder.clear();
        }

    }


    public ActivityUserRecord checkUser(String activityId, String openId, String mobile, String taskBizType) {
        log.info("校验活动用户参与活动 activityId:{},openId:{}, mobile:{}, taskBizType:{}", activityId, openId, mobile, taskBizType);
        if (StringUtils.isNotBlank(mobile)) {
            return findByMobile(activityId, mobile, taskBizType, openId);

        }
        ActivityUserRecord activityUserRecord = findByOpenId(activityId, openId, taskBizType);
        log.info("校验活动用户参与活动 activityUserRecord:{}", JSONObject.toJSONString(activityUserRecord));
        if (activityUserRecord.getMobileVerify()) {
            throw new MobileUserException(activityUserRecord.getMobile());
        }
        return activityUserRecord;
    }

    public ActivityUserRecord detail(String id) {
        ActivityUserRecord activityUserRecord = this.mongoTemplate.findById(id, ActivityUserRecord.class);
        if (Objects.isNull(activityUserRecord)) {
            return null;
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").is(activityUserRecord.getActivityId()));
        List<CertificateActivityConfig> certificateActivityConfigList = this.mongoTemplate.find(query,
                CertificateActivityConfig.class);
        if (CollectionUtils.isNotEmpty(certificateActivityConfigList)) {
            activityUserRecord.setCertificateActivityConfigList(certificateActivityConfigList);
        }
        return activityUserRecord;
    }

    public void edit(ActivityUserRecord activityUserRecord) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(activityUserRecord.getId()));
        ActivityUserRecord exist = mongoTemplate.findOne(query, ActivityUserRecord.class);
        if (Objects.isNull(exist)) {
            return;
        }
        this.mongoTemplate.save(activityUserRecord);
        cacheActivityUserRecordService.removeMobile(activityUserRecord.getActivityId(), activityUserRecord.getMobile()
                , activityUserRecord.getTaskBizType());
        cacheActivityUserRecordService.removeOpenId(activityUserRecord.getActivityId(), activityUserRecord.getOpenId()
                , activityUserRecord.getTaskBizType());
        orderService.updateByMobileAndActivityId(exist.getMobile(), activityUserRecord.getMobile(),
                exist.getActivityId(), activityUserRecord.getName(), activityUserRecord.getUniversityId(),
                activityUserRecord.getUniversityName(), exist.getUserId());
        userCaRecordService.updateByMobileAndActivityId(exist.getMobile(), activityUserRecord.getMobile(),
                exist.getActivityId(), activityUserRecord.getName(), activityUserRecord.getUniversityId(),
                activityUserRecord.getUniversityName());

    }

    public void updateByMobileAndActivityId(String mobile, String toMobile, String activityId,
                                            String name, String universityId, String universityName,
                                            String userId) {
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(activityId)) {
            return;
        }
        Query query = new Query().addCriteria(Criteria.where("mobile").is(mobile).and("activityId").is(activityId));
        if (StringUtils.isNotBlank(userId)) {
            query.addCriteria(Criteria.where("userId").is(userId));
        }
        List<ActivityUserRecord> datas = mongoTemplate.find(query, ActivityUserRecord.class);
        if (CollectionUtils.isEmpty(datas)) {
            return;
        }
        Update update = new Update();
        Date date = new Date();
        boolean toUpdate = false;
        if (StringUtils.isNotBlank(name)) {
            update.set("name", name);
            toUpdate = true;
        }
        if (StringUtils.isNotBlank(universityId)) {
            update.set("universityId", universityId);
            toUpdate = true;
        }
        if (StringUtils.isNotBlank(universityName)) {
            update.set("universityName", universityName);
            toUpdate = true;
        }
        if (!mobile.equals(toMobile)) {
            update.set("mobile", toMobile);
            toUpdate = true;
        }
        if (toUpdate) {
            update.set("updatedTime", date);
            UpdateResult updateResult = mongoTemplate.updateMulti(query, update, ActivityUserRecord.class);
            if (updateResult.getModifiedCount() > 0) {
                for (ActivityUserRecord a : datas) {
                    cacheActivityUserRecordService.removeMobile(a.getActivityId(), a.getMobile()
                            , a.getTaskBizType());
                    cacheActivityUserRecordService.removeOpenId(a.getActivityId(), a.getOpenId()
                            , a.getTaskBizType());
                }
            }
        }

    }
}
